﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WordpressDemo.Models;
using WordpressRestApi;

namespace WordpressDemo.Controllers
{
    public class DemoReadController : Controller
    {
        public async Task<ActionResult> Index()
        {
            var identity = User.Identity as IdentityModel;
            //  Grab the wordpress client
            var client = identity.GetWordpressClient();
            var posts = await GetPostsAsync(client);
            var tags = await GetTagsAsync(client);
            var model = new DemoReadViewModel
            {
                Identity = identity,
                Posts = posts,
                Tags = tags
            };

            return View(model);
        }

        private async static Task<IEnumerable<TagInfo>> GetTagsAsync(WordpressClient client)
        {
            //  Grab the tag client and query tags on it
            //  This instruction doesn't go to the service yet
            var tagQuery = client.Tag.GetAllTags();
            //  Asynchronously fetch all tags
            var allTags = await tagQuery.ToArrayAsync();
            var sortedTags = from t in allTags
                             orderby t.PostCount descending
                             select t;

            return sortedTags;
        }

        private async static Task<IEnumerable<PostInfo>> GetPostsAsync(WordpressClient client)
        {
            //  Grab the post client and query posts on it
            //  This instruction doesn't go to the service yet
            var postQuery = client.Post.GetPosts(new PostParametrization
            {
                Status = PostStatus.Publish,
                OrderByField = PostField.Title,
                OrderByAscending = true,
                Fields = new[] { PostField.Title, PostField.Url }
            });
            //  We can refined the query, although not with LINQ queries since we
            //  operate on an asynchronous collection
            var postRefinedQuery = postQuery
                .Where(p => !p.Title.Contains("Private Title"))
                .Select(p => new { p.Title, p.Url, Post = p });
            //  We finally asynchronously fetch the first 5 elements
            var posts = await postRefinedQuery.ToArrayAsync(5);

            //  We fetch the post back (the select was useless and just to demonstrate)
            return from p in posts select p.Post;
        }
    }
}